/**
 * JavaScript LazyLoad Library v0.1
 * Copyright (c) 2011 snandy
 * Blog: http://www.cnblogs.com/snandy
 * QQ群: 34580561
 * Date: 2011-04-26
 * 
 * 加载多个js后才回调，有个缺陷是js文件不存在，那么也将触发回调
 * 
 * 接口
 * LazyLoad.js(
 * 	 urls  // js文件路径
 *   fn    // 全部加载后回调函数
 *   scope // 指定回调函数执行上下文
 * );
 * 
 * 示例
 * LazyLoad.js(['a.js','b.js','c.js'], function(){
 * 		console.log('加载完毕');
 * }, scope);
 * 
 */

LazyLoad = function(win){	
	var list,
		isIE = /*@cc_on!@*/!1,
		doc = win.document,
		head = doc.getElementsByTagName('head')[0];

	function createEl(type, attrs){
		var el = doc.createElement(type),
			attr;
		for(attr in attrs){
			el.setAttribute(attr, attrs[attr]);
		}
		return el;
	}
	function finish(obj){
		list.shift();
		if(!list.length){
			obj.fn.call(obj.scope);
		}
	}
	function js(urls, fn, scope){
		list = [].concat(urls);
		var obj = {scope:scope||win, fn:fn};
		for(var i=0,len=urls.length; i<len; i++){
			var script = createEl('script', {src: urls[i]});
			if(isIE){
				script.onreadystatechange = function(){
					var readyState = this.readyState;
					if (readyState == 'loaded' || readyState == 'complete'){
						this.onreadystatechange = null;
						finish(obj);
						
					}
				}
			}else{
				script.onload = script.onerror = function(){
					finish(obj);
				}
			}
			head.appendChild(script);
		}
	}

	return {js:js};
}(this);
